package com.foreknow.service;

import com.foreknow.dao.impl.UserDaoImpl;
import com.foreknow.entity.User;
import com.foreknow.util.DbHelper;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class UserService {
    private UserDaoImpl userDaoImpl;

    public UserService(){
        userDaoImpl = new UserDaoImpl();
    }

    public User Login(String account,String password){
        String sql = "select * from user where account=? and password=?";
        List<User> list = null;
        try {
            list = userDaoImpl.queryByCondition(sql,account,password);
            if (list.size()>0) {
                return list.get(0);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public boolean Register(User user){
        DataSource dataSource = DbHelper.getDataSource();
        Connection conn = null;
        String sql = "insert into user(username,account,password,phone,email,avater) value(?,?,?,?,?,?)";
        int isRight = 0;
        Object[] params = {user.getUsername(),user.getAccount(),user.getPassword(),user.getPhone(),user.getEmail(),user.getAvater()};
        try {
            conn = dataSource.getConnection();
            isRight = userDaoImpl.insert(sql,params);
            conn.commit();
        } catch (SQLException e) {
            try {
                conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        }
        return isRight==1;
    }

    public User getUserByID(Integer id){
        String sql = "select * from user where id=?";
        try {
            return userDaoImpl.queryOne(sql,id);
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    public User getUserByName(String username){
        String sql = "select * from user where username = ?";
        try {
            return userDaoImpl.queryOne(sql,username);
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    public Integer updateUser(User user){
        String sql = "update user set username = ?,account = ?,password = ?,phone = ?,email = ?,avater = ? where id = ?";
        try {
            return userDaoImpl.update(sql,user.getUsername(),user.getAccount(),user.getPassword(),user.getPhone(),user.getEmail(),user.getAvater(),user.getId());
        } catch (SQLException e) {
            e.printStackTrace();
            return -1;
        }
    }


}
